package com.yc.started.login.biz;

import com.yc.started.login.LoginProperties;
import com.yc.started.login.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class AuthBiz {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    LoginProperties properties;

    public Object login(String username, String password){
        // 验证
        Utils.checkEmpty(username, "账号不能为空")
                .checkEmpty(password, "密码不能为空")
                .check(username.length()<2, "账号长度不能小于2")
                .check(password.length()<6, "密码长度不能小于6");

        // 动态拼接sql
        String sql = "select *" +
                "  from " + properties.getUserTable() +
                " where " + properties.getUsernameColumn() + " = ?" +
                "   and " + properties.getPasswordColumn() + " = ?";

        // 执行查询
        Object ret = null;
        try{
            if(properties.getUserClass() == null){
                ret = jdbcTemplate.queryForMap(sql,username,password);
            } else {
                // 查询结果封装为一个实体对象
                ret = jdbcTemplate.queryForObject(sql,
                        new BeanPropertyRowMapper<>(properties.getUserClassObject()),
                        username,password);
            }
        } catch (DataAccessException e) {
            // mybatis 查询一个对象时, 如果没有查询到数据, 返回是 null
            // spring 查询一个对象时, 如果没有查询到数据, 是抛出异常
            throw new BizException("用户名或密码错误",e);
        }
        return ret;
    }


}
